package com.application.outdoor.InvoikeServices;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.application.Activity.MESApplication;
import com.application.Network.Protocol;

public class AvatarInvoike extends BaseInvoike{
	private String avatarPath;
	public AvatarInvoike(){
		super();
		url+="/AvatarServlet";
		avatarPath=MESApplication.getAvatarDir();
	}
	public void getAvatar(String userName) throws Exception{
		Log.d(Protocol.TAG,"getAvatar "+userName);
		URL url = new URL(this.url + "?" + Protocol.CMD + "=" + Protocol.DOWNLOAD+"&"+Protocol.NGUOI_DUNG+"="+userName);
		URLConnection connection = url.openConnection();
		connection.connect();
		InputStream input = new BufferedInputStream(url.openStream());
		
		int fileLength = connection.getContentLength();
		if (fileLength > 0) {
			File file=new File(avatarPath+"/"+userName+".png");
			OutputStream output = new FileOutputStream(file);

			byte data[] = new byte[1024];			
			int count;		
			while ((count = input.read(data)) != -1) {
				output.write(data, 0, count);
			}

			output.flush();
			output.close();
			input.close();
		}
	}
	public void setAvatar(String userName, String path) throws IOException,ClientProtocolException{		
		OutputStream os;
		
			//Copy file vào thư mục avatar và resize còn 32x32
			Bitmap bmIn=BitmapFactory.decodeFile(path);
			Bitmap bmOut=Bitmap.createScaledBitmap(bmIn, 32, 32, true);
			os = new FileOutputStream(avatarPath+"/"+userName+".png");
			bmOut.compress(CompressFormat.PNG, 100, os);
			os.flush();
			os.close();
			
			//Up lên server
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			
			MultipartEntity multipartContent=new MultipartEntity();
			multipartContent.addPart(Protocol.NGUOI_DUNG, new StringBody(userName));
			multipartContent.addPart(Protocol.CMD,new StringBody(Protocol.UPLOAD));
			multipartContent.addPart("file", new FileBody(new File(avatarPath+"/"+userName+".png")));
			
			httpPost.setEntity(multipartContent);
			httpClient.execute(httpPost);
			Log.d(Protocol.TAG,"Đã setAvatar thànhh công");
		
	}
}
